package com.sdp.irrigation.server.netty.encode;

import com.sdp.irrigation.utils.CommConstants;
import com.sdp.irrigation.utils.JsonUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonMessageEncoder extends MessageToByteEncoder<Object> {
	
	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
		ByteBuf buf = null;
		try {
			String jsonString = JsonUtils.toJSONString(msg);
			log.info("通道id： {},  下行消息： {}", ctx.channel().id().toString(), jsonString);
			// 将 JSON 字符串写入 ByteBuf
	        byte[] bytes = jsonString.getBytes("UTF-8");
	        out.writeBytes(bytes);
			out.writeBytes(CommConstants.JSON_DELIMITER.getBytes("UTF-8"));
		}
		finally
		{
			if (buf != null) {
				buf.release();
			}
		}
	}

}
